﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Microsoft.SqlServer;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using Eb.MessageBox;

//Microsoft.SqlServer.Management.Common.ConnectionManager
public partial class Modules_CreateDatabase : System.Web.UI.UserControl
{
#region Fields

    DbCreator objDBCreate;
    string ConnStr=string.Empty;
    bool IsDBCreated=false;
#endregion

    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
    {
        if(Wizard1.ActiveStep.Name=="Run SQL Script")
        {
            string sqlpath=Server.MapPath(txtSQLPath.Text);
            objDBCreate=new DbCreator();
            //  First Create the Connection String from Previous Steps Settings
            string StrCon=string.Empty;
            if( ViewState["ConStr"]!=null)
                StrCon =( ViewState["ConStr"].ToString()) + "Database=" + txtDBName.Text + ";";
            //Run the SQL Script
            if(objDBCreate.ExecuteSQLScript(sqlpath, StrCon)) 
                MessageBox.Show("SQL Script Execute Successfully..");
            else
                MessageBox.Show("There is an error into script file.");
        }
    }

    private bool CheckAndCreateDatabase(string servername,string userid,string password,string database)
    {
        if (TestConnection(servername, userid, password, database) == true)
        {
            //check Server name and database name are not empty.
            if (!string.IsNullOrEmpty(txtServer.Text) & !string.IsNullOrEmpty(txtDBName.Text))
            {
                Server oServer = new Server();


                Microsoft.SqlServer.Management.Common.ServerConnection oServerConnection = new Microsoft.SqlServer.Management.Common.ServerConnection(txtServer.Text);

                oServerConnection.ConnectionString = ConnStr;
                oServerConnection.Connect();

                oServer = new Server(oServerConnection);

                //Database db = new Database();

                //========= check for DB Existance
                foreach (Database db in oServer.Databases)
                {
                    if (database == db.Name)
                    {
                        //    CreateMessageAlert(this.Page, "The database already exist, try with another name..", "Database");
                        MessageBox.Show("The database already exist, try with another name.." + "Database");
                        return false;
                    }
                }

                //create the database procedure goes here.
                objDBCreate = new DbCreator();

                if (objDBCreate.CreateSQLDb(servername, database, userid, password) == true)
                {
                    ViewState.Add("ConStr", ConnStr);
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
           
        }
        return false;
    }
    
    
    

   private bool TestConnection(string servername, string userid, string password, string databasename)
   {
       //check for windows authentication mode.
       if (ddlAuthenticationMode.SelectedValue == "1") {
           ConnStr = "Persist Security Info=False;Integrated Security=SSPI;Data Source=" + servername + ";";
       }
       //check for sql server authentication mode.
       if (ddlAuthenticationMode.SelectedValue == "0") {
           ConnStr = "Persist Security Info=False;User ID=" + userid + ";pwd=" + password + ";Data Source=" + servername + ";";
       }
      
       string str = ConnStr;

       System.Data.SqlClient.SqlConnection Conn = new System.Data.SqlClient.SqlConnection();
       Conn.ConnectionString = ConnStr;

       if (Conn.State == System.Data.ConnectionState.Closed)
       {
           Conn.Open();
           return true;
       }
       else {
           //CreateMessageAlert(this.Page, "Test connection failed for Server : " + txtServer.Text, "Database");
           MessageBox.Show("Test connection failed for Server : " + txtServer.Text + "Database");
          return false;
       }
   }


   protected void Wizard1_NextButtonClick1(object sender, WizardNavigationEventArgs e)
   {
       if (Wizard1.ActiveStep.Name == "Database Configuration")
       {
           //========= Check DB Exits or not
           if (CheckAndCreateDatabase(txtServer.Text, txtUserID.Text, txtPassword.Text, txtDBName.Text) == true)
           {
               IsDBCreated = true;
               MessageBox.Show("Database Created Successfully.");
           }
           else
           {
           }
       }
   }
}
